<template>
	<ls-skeleton :loading="loading">
		<view class="container">
			<view class="uni-list a">
				<view class="uni-list-cell uni-list-cell-pd" @click="getAddress">
					<image mode="widthFix" src="../../../static/images/pro_12.png" class="pic"></image>
					<view class="uni-list-cell-db" v-if="addressId > 0">
						<view class="h3">{{addressInfo.receiveName}} {{addressInfo.receivePhone}}</view>
						<view v-if="addressInfo.address">
							{{addressInfo.provinceName + '/' + addressInfo.cityName + '/' + addressInfo.districtName + ' ' + addressInfo.address}}
						</view>
					</view>
					<view v-else class="uni-list-cell-db">设置收货地址</view>
					<view class="uni-navigate-right"></view>
				</view>
			</view>
			<view class="uni-list b">
				<view class="uni-list-cell uni-list-cell-pd">
					<image mode="widthFix" :src="productDetail.productImage" class="pic"></image>
					<view class="uni-list-cell-db">
						<view class="h3">{{productDetail.productName}}</view>
						<view class="h4">{{productDetail.specifications}}</view>
						<view class="p uni-flex">
							<!-- 2024-01-24 -->
							<!-- <view class="uni-flex-item" v-if="userType == 'STORE'">￥{{productDetail.productPrice}}</view> -->
							<!-- 							<view class="uni-flex-item" v-if="userType == 'STORE'">￥{{productDetail.salePrice}}</view>
							<view class="uni-flex-item" v-else>￥{{productDetail.proxyPrice}}</view> -->
							<view class="uni-flex-item" v-if="productDetail.proxyPrice && userType == 'STORE'">
								￥{{productDetail.proxyPrice||0}}</view>
							<view class="uni-flex-item" v-else-if="productDetail.productPrice && userType == 'SALE'">
								￥{{productDetail.productPrice||0}}</view>
							<view class="uni-flex-item" v-else>￥{{productDetail.salePrice||0}}</view>

							<view>×{{buyNumber}}</view>
						</view>
					</view>
				</view>
				<view class="uni-list-cell uni-list-cell-pd">
					<view class="uni-list-cell-db">
						<view class="uni-inline-item pd-tb-5">
							<view class="uni-flex-item">数量：</view>
							<view>{{buyNumber}}</view>
						</view>
						<view class="uni-flex pd-tb-5" v-if="isYunFei">
							<view class="uni-flex-item">运费：</view>
							<view>￥{{freight_fee}}</view>
						</view>
						<view class="uni-flex pd-tb-5">
							<view class="uni-flex-item">总价：</view>
							<text>￥{{price}}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="uni-inline-item"
				style="display: flex;justify-content: center; align-items: center; color: #999999;">
				<text>金额超过500元免运费</text>
			</view>
			<view class="footer">
				<u-button type="primary" color="#06A972" text="立即支付" :disabled="disabled"
					@click="createOrder"></u-button>
			</view>
		</view>
	</ls-skeleton>
</template>


<script>
	import {
		toLogin,
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";
	import {
		HEADER,
		HTTP_REQUEST_URL,
	} from '@/config/app';
	import {
		quickSubmit,
		xcxPay,
		amountPay,
		paySuccessPrint
	} from '@/api/order.js';
	import {
		getAddress,
		getDefault
	} from '@/api/userAddr.js';
	import {
		getParam
	} from '@/api/common.js';
	import {
		getUserAmount,
		getUserInfo
	} from '@/api/user.js';
	export default {
		data() {
			return {
				addressInfo: {},
				addressId: 0,
				productDetail: {},
				buyNumber: 0,
				price: 0,
				disabled: false,
				type: '',
				freight_limit: 0,
				freight_fee: 0,
				userAmount: {},
				is_balance: true,
				loading: true,
				not_yunfeiList: [],
				isYunFei: true
			}
		},
		computed: mapGetters(['isLogin', 'uid', 'userType']),
		async onLoad(options) {
			const that = this;
			if (that.isLogin == false) {
				toLogin();
			}
			// 运费
			that.freight_limit = await that.getParam('XCX_FREIGHT_LIMIT');
			that.freight_fee = await that.getParam('XCX_FREIGHT_FEE');
			// 获取用户余额
			that.getUserAmount();


			//获取不需要运费的批发商
			let notYunFeiListStr = await that.getParam('XCX_NO_YUNFEI');

			// 将字符串解析为数组
			try {
				that.not_yunfeiList = JSON.parse(notYunFeiListStr);
			} catch (error) {
				console.error('解析 not_yunfeiList 时出错:', error);
				that.not_yunfeiList = []; // 如果解析失败，设置为空数组
			}

			await getUserInfo({
				userInfoId: that.uid,
			}).then(res => {
				if (res.value.frontUserPhone) {
					that.not_yunfeiList.forEach(item => {
						if (`${item}` === `${res.value.frontUserPhone}`) {
							that.isYunFei = false;
						}
					})
				}
			})

			that.productDetail = JSON.parse(decodeURIComponent(options.detail)) || {};
			that.buyNumber = options.buyNumber || 0;
			that.type = options.type;
			console.log(options.type);
			if (!Object.keys(that.productDetail).length) {
				return that.$util.Tips({
					title: '数据无效'
				}, {
					tab: 3
				});
			}

			if (that.type == 'STORE') {
				// 2024-01-24
				// that.price = that.$util.$h.Mul(that.buyNumber, that.productDetail.productPrice || 0);
				that.price = that.$util.$h.Mul(that.buyNumber, that.productDetail.proxyPrice || 0);
			} else if (that.type == 'SALE') {
				that.price = that.$util.$h.Mul(that.buyNumber, that.productDetail.productPrice || 0);
			} else {
				that.price = that.$util.$h.Mul(that.buyNumber, that.productDetail.salePrice || 0);
			}

			if (that.isYunFei) {
				// 运费
				if (that.price < that.freight_limit) {
					that.price = that.$util.$h.Add(that.price, that.freight_fee);
				}
			}
		},

		onShow() {
			let that = this;
			uni.$on('addressId', function(addressId) {
				that.addressId = addressId
			})
			that.getaddressInfo();
		},

		methods: {

			async createOrder() {
				let that = this;
				that.disabled = true;
				let orderId = 0;

				if (that.addressId == 0) {
					that.disabled = false;
					return that.$util.Tips({
						title: '请选择收货地址',
					});
				}

				// #ifdef MP
				if (that.is_balance && that.userAmount.totalPrice > that.price) {
					// 余额支付
					if (that.userAmount.totalPrice < that.price) {
						return that.$util.Tips({
							title: '余额不足，请前去充值',
						}, {
							tab: 5,
							url: '/pages/users/user_payment/index'
						});
					} else {
						uni.showModal({
							title: "余额支付",
							content: `您本次需要支付${that.price}`,
							success: (async res => {
								if (res.confirm) {
									uni.showLoading({
										title: '订单支付中'
									});
									// 创建订单
									orderId = await that.quickSubmit();
									// 余额支付
									that.amountPay(orderId);
								} else {
									that.disabled = false;
								}
							})
						})
					}
				} else {
					uni.showLoading({
						title: '订单支付中'
					});
					orderId = await that.quickSubmit();
					// 微信支付
					that.payment(orderId);
				}
				// #endif

			},

			/**
			 * 创建订单
			 */
			quickSubmit() {
				let that = this;
				return new Promise((resolve, reject) => {
					quickSubmit({
						proDetailId: that.productDetail.proDetailId,
						buyNumber: parseInt(that.buyNumber),
						userInfoId: that.uid,
						addressId: that.addressId
					}).then(res => {
						resolve(res.value);
					}).catch(err => {
						reject(err)
					});
				})
			},

			createOrder1() {
				let that = this;
				that.disabled = true;
				if (that.addressId == 0) {
					return that.$util.Tips({
						title: '请选择收货地址'
					});
				}
				quickSubmit({
					proDetailId: that.productDetail.proDetailId,
					buyNumber: parseInt(that.buyNumber),
					userInfoId: that.uid,
					addressId: that.addressId
				}).then(res => {
					that.disabled = true;
					// #ifdef MP
					if (that.is_balance) {
						// 余额支付
						if (!(that.userAmount.totalPrice < that.price)) {
							return that.$util.Tips({
								title: '余额不足，请前去充值',
							}, {
								tab: 5,
								url: '/pages/users/user_payment/index'
							});
						} else {
							uni.showModal({
								title: "余额支付",
								content: `您本次需要支付${that.price}`,
								success(res) {
									if (res.confirm) {
										uni.showLoading({
											title: '订单支付中'
										});
										that.amountPay(res.value);
									} else {
										that.disabled = false;
									}
								}
							})
						}
					} else {
						uni.showLoading({
							title: '订单支付中'
						});
						// 微信支付
						that.payment(res.value);
					}
					// #endif
				}).catch(err => {
					that.$util.Tips({
						title: err
					});
				})
			},

			/**
			 * 余额支付
			 * @param {Object} orderId
			 */
			amountPay(orderId) {
				console.log(orderId);
				let that = this;
				amountPay({
					userInfoId: that.uid,
					orderId: orderId
				}).then(res => {

					uni.hideLoading();
					let goPages = '/pages/users/order_list/index?type=';
					// goPages += '?orderId=' + orderId;
					paySuccessPrint({
						orderId: orderId,
					}).then(res => {

					})
					return that.$util.Tips({
						title: '支付成功',
						icon: 'success'
					}, {
						tab: 5,
						url: goPages + "WAIT_SEND"
					});
				}).catch(err => {
					uni.hideLoading();
					that.$util.Tips({
						title: err
					});
				})
			},

			/**
			 * 微信支付
			 * @param {Object} orderId
			 */
			payment(orderId) {
				console.log(orderId);
				let that = this;
				xcxPay({
					orderId: orderId,
					userInfoId: that.uid,
				}).then(res => {
					let goPages = '/pages/users/order_list/index?type=';
					// goPages += '?orderId=' + orderId;
					let jsConfig = res.value.param;
					// #ifdef MP
					uni.requestPayment({
						timeStamp: jsConfig.timeStamp,
						nonceStr: jsConfig.nonceStr,
						package: jsConfig.package,
						signType: jsConfig.signType,
						paySign: jsConfig.paySign,
						success: function(res) {
							uni.hideLoading();
							paySuccessPrint({
								orderId: orderId,
							}).then(res => {

							})
							return that.$util.Tips({
								title: '支付成功',
								icon: 'success'
							}, {
								tab: 5,
								url: goPages + "WAIT_SEND"
							});
						},
						fail: function(e) {
							console.log(e)
							console.log("取消支付");
							// 调用后端接口，更新订单状态为待支付
							uni.request({
								url: HTTP_REQUEST_URL + '/api/order/cancelPayment',
								// url: HTTP_REQUEST_URL + '/order/cancelPayment',
								method: 'POST',
								data: {
									orderId: orderId
								},
								success: () => {
									console.log('订单状态更新为待支付');
								},
							});
							uni.hideLoading();
							return that.$util.Tips({
								title: '取消支付'
							}, {
								tab: 5,
								url: goPages + 'WAIT_PAY'
							});
						},
						complete: function(e) {
							uni.hideLoading();
							//关闭当前页面跳转至订单状态
							if (res.errMsg == 'requestPayment:cancel') return that.$util
								.Tips({
									title: '取消支付'
								}, {
									tab: 5,
									url: goPages + 'WAIT_PAY'
								});
						},
					})
					// #endif
				}).catch(err => {
					that.$util.Tips({
						title: err.msg
					});
				})
			},

			/**
			 * 获取参数
			 * @param {Object} paramType
			 */
			getParam(paramType) {
				return new Promise((resolve, reject) => {
					getParam({
						paramType: paramType
					}).then(res => {
						resolve(res.value);
					}).catch(err => {
						reject(err);
					})
				});
			},

			/**
			 * 获取余额
			 */
			getUserAmount() {
				let that = this;
				getUserAmount({
					userInfoId: that.uid
				}).then(res => {
					that.userAmount = res.value;
				})
			},

			getAddress() {
				this.$util.Tips('/pages/goods/address/index');
			},

			/*
			 * 获取默认收货地址或者获取某条地址信息
			 */
			getaddressInfo() {
				let that = this;
				if (that.addressId) {
					getAddress({
						userInfoId: that.uid,
						addressId: that.addressId
					}).then(res => {
						that.loading = false;
						that.addressInfo = res.value || {};
						that.addressId = that.addressInfo.addressId ? res.value.addressId || 0 : 0;
					}).catch(err => {
						that.$util.Tips({
							title: err
						})
					})
				} else {
					getDefault({
						userInfoId: that.uid
					}).then(res => {
						that.loading = false;
						that.addressInfo = res.value || {};
						that.addressId = res.value.addressId || 0;
					}).catch(err => {
						that.$util.Tips({
							title: err
						})
					})
				}
			},

		}
	}
</script>

<style>
	page {
		background: #F3F3F3;
	}

	.container {
		padding: 20rpx;
	}

	.container .uni-list {
		border-radius: 20rpx;
		margin-bottom: 20rpx;
	}

	.container .a image {
		width: 21rpx;
		height: 25rpx;
		margin-right: 30rpx;
	}

	.container .a .h3 {
		font-weight: bold;
	}

	.container .a .h3 text {
		padding-left: 30rpx;
	}

	.container .b .pic {
		width: 148rpx;
		height: 168rpx;
		margin-right: 20rpx;
	}

	.container .b .h3 {
		line-height: 40rpx;
		font-weight: bold;
	}

	.container .b .h4 {
		font-size: 24rpx;
		color: #868686;
		margin-top: 3px;
	}

	.container .b .p .uni-flex-item {
		font-size: 32rpx;
		font-weight: bold;
		color: #E91E1E;
	}

	.container .b .uni-inline-item {
		color: #BDBDBD;
	}

	.container .b .uni-flex text {
		font-size: 32rpx;
		font-weight: bold;
	}

	.pd-tb-5 {
		padding: 5rpx 0;
	}

	.bottom {
		font-size: 24rpx;
		line-height: 36rpx;
		position: fixed;
		z-index: 99;
		left: 0;
		bottom: 0;
		padding: 10rpx 30rpx;
		background-color: #fff;
		box-sizing: border-box;
		width: 100%;
	}
</style>